import requests
import json

def get_example():
    """GET请求示例"""
    # 简单GET请求
    response = requests.get('https://api.github.com/events')
    print(f"GET状态码: {response.status_code}")
    print(f"GET响应内容: {response.json()[:2]}\n")  # 只显示前两条数据
    
    # 带参数的GET请求
    params = {
        'q': 'python',
        'sort': 'stars'
    }
    response = requests.get('https://api.github.com/search/repositories', params=params)
    print(f"带参数GET状态码: {response.status_code}")
    print(f"查询URL: {response.url}\n")

def post_example():
    """POST请求示例"""
    # 发送JSON数据
    data = {
        'name': 'test',
        'description': 'test post request'
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(
        'https://httpbin.org/post',
        data=json.dumps(data),
        headers=headers
    )
    print(f"POST状态码: {response.status_code}")
    print(f"POST响应内容: {response.json()}\n")

def other_methods():
    """其他HTTP方法示例"""
    # PUT请求
    response = requests.put('https://httpbin.org/put', data={'key': 'value'})
    print(f"PUT状态码: {response.status_code}")
    
    # DELETE请求
    response = requests.delete('https://httpbin.org/delete')
    print(f"DELETE状态码: {response.status_code}")

def error_handling():
    """错误处理示例"""
    try:
        response = requests.get('https://api.github.com/invalid', timeout=5)
        response.raise_for_status()  # 抛出HTTP错误状态
    except requests.exceptions.HTTPError as http_err:
        print(f'HTTP错误发生: {http_err}')
    except requests.exceptions.ConnectionError as conn_err:
        print(f'连接错误: {conn_err}')
    except requests.exceptions.Timeout as timeout_err:
        print(f'超时错误: {timeout_err}')
    except requests.exceptions.RequestException as err:
        print(f'其他错误: {err}')

if __name__ == '__main__':
    print("=== GET请求示例 ===")
    get_example()
    
    print("=== POST请求示例 ===")
    post_example()
    
    print("=== 其他HTTP方法示例 ===")
    other_methods()
    
    print("=== 错误处理示例 ===")
    error_handling() 